//
//  NewspaperInfoViewController.m
//  JianChaRiBao
//
//  Created by 常兴宇 on 13-10-29.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "NewspaperInfoViewController.h"
#import "AppDelegate.h"
#import "PicVersion.h"
#import "NewspaperTitleCell.h"
#import "NewspaperDesCell.h"
#import "NewspaperPicDesViewController.h"
#import "NewspaperSingleArticleViewController.h"
#import "DownloadArticle.h"
#import "UIImageView+WebCache.h"
#import "MagazineInfoViewController.h"
#import "JinRiMagazineHistoryViewController.h"
#import "DataBase.h"
#import "ASIDownloadCache.h"
@interface NewspaperInfoViewController ()
{
    NSMutableArray * textVersionArray;
    NSString * item_id;
}
@end

@implementation NewspaperInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        shouldSwipeBack = YES;
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectCell:) name:@"didSelectNewsCell" object:nil];
   
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadComplete:) name:KDownloadComplete object:nil];

    
    }
    return self;
}
-(void)downloadComplete:(NSNotification *)notification{
    

    ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"下载完成"]autorelease];
    [abp show];
    [leftDownloadButton setTitle:@"已下载" forState:UIControlStateNormal];
    leftDownloadButton.enabled = NO;
}


- (IBAction)backButtonClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    downloadButton.hidden = YES;
    
    if (self.titleStr) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.baseInfo];
        [dic setObject:self.titleStr forKey:@"pub_date"];
        self.baseInfo = dic;
    }
    
    item_id = [[self.baseInfo objectForKey:@"item_id"]retain];

    NSLog(@"baseInfo:%@",self.picVersionArray);
    if (self.isHomePage) {
        backButton.hidden = YES;
//        [self loadImage];
        [self getHomePageData];
    }else{
        
        int count =  [self.picVersionArray indexOfObject:self.baseInfo];
        [picGridView setContentOffset:CGPointMake(320 * count, 0) animated:YES];
        [self reloadView];
    }
    
    
}
- (void)loadImage{
//    headImage.layer.shadowColor = [UIColor blackColor].CGColor;
//    headImage.layer.shadowOpacity = 0.45;
//    headImage.layer.shadowOffset = CGSizeMake(0, 6);
//    headImage.layer.shadowPath = [UIBezierPath bezierPathWithRect:headImage.bounds].CGPath;
//    headImage.layer.masksToBounds = NO;
}
-(void)awakeFromNib{
}
-(void)getHomePageData{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] getHistoryInfo:NEWSPAPERID];
//        NSLog(@"obj:%@",obj);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([obj isKindOfClass:[NSDictionary class]] && [[obj objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                historyInfo = [[NSArray alloc]initWithArray:[obj objectForKey:@"result"]];
                
                self.magazineInfo = [[obj objectForKey:@"result"] objectAtIndex:0];
                self.titleStr = [NSString stringWithFormat:@"%@%@",[self.magazineInfo objectForKey:@"magazinename"],[self.magazineInfo objectForKey:@"sourcenum"]];
                [self reloadView];

                
                NSMutableString * str = [NSMutableString stringWithString:[self.magazineInfo objectForKey:@"image"]];
                NSRange range = [str rangeOfString:@"cover"];
                if (range.location != NSNotFound) {
                    [str replaceCharactersInRange:range withString:@"cover_512"];
                }
                [headImage setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"Default - 1x.png"]];
                [self loadImage];

                NSLog(@"url:%@",str);
                historyButton.enabled = YES;
                leftDownloadButton.enabled = YES;

                
                NSArray * array = [[DataBase shareDB]selectMagaInfo];
                NSMutableArray * downloadArray = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary * dict in array) {
                    ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,[[AuthorManager defaultManager] userID],[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
                    if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
                        [downloadArray addObject:dict];
                    }
                }
                for (NSDictionary * dict in downloadArray) {
                    if ([[dict objectForKey:@"magitemid"]isEqualToString:[self.magazineInfo objectForKey:@"magitemid"]]) {
                        [leftDownloadButton setTitle:@"已下载" forState:UIControlStateNormal];
                        leftDownloadButton.enabled = NO;
                        return ;
                    }
                }
                
                
            }

        
        });
    });

}

- (void)reloadView{
    NSLog(@">>>>>>>>>title:%@",self.titleStr);
    titleLabel.scrollType = ScrollSingle;
    titleLabel.font = [UIFont systemFontOfSize:21.0f];
    titleLabel.text = self.titleStr;
    [titleLabel startScroll];
    
    picVersionsButton.selected = YES;
    picGridView.layoutDirection = AQGridViewLayoutDirectionHorizontal;
    picGridView.pagingEnabled = YES;
    picGridView.requiresSelection = NO;
    picGridView.showsHorizontalScrollIndicator = NO;
    picGridView.showsVerticalScrollIndicator = NO;
//    [picGridView reloadData];

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch * touch = [touches anyObject];
//    NSLog(@"touch:%@",touch.view);
    if (touch.view == headImage) {
        
        MagazineInfoViewController *magazineInfoViewController = [[[MagazineInfoViewController alloc]initWithNibName:@"MagazineInfoViewController" bundle:nil]autorelease];
        magazineInfoViewController.basicInfo = self.magazineInfo;
        [[UIApplication rootNavController] pushViewController:magazineInfoViewController animated:YES];
        
    }
}


- (IBAction)historyButtonClicked:(id)sender {
    JinRiMagazineHistoryViewController * jinRiMagazineHistoryViewController = [[[JinRiMagazineHistoryViewController alloc]initWithNibName:@"JinRiMagazineHistoryViewController" bundle:nil]autorelease];
    jinRiMagazineHistoryViewController.histroyArray = historyInfo;
    [[UIApplication rootNavController]pushViewController:jinRiMagazineHistoryViewController animated:YES];
    
    
}
- (IBAction)leftDownloadButtonClicked:(id)sender {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];

        if ([self.magazineInfo objectForKey:@"magitemid"]){
            id obj = [[DataRequest sharedRequest]getMagazineContent:[self.magazineInfo objectForKey:@"magitemid"]];
            NSLog(@"obj:%@",obj);
            if ([obj isKindOfClass:[NSDictionary class]] && [[obj objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                NSArray *_contentArray = [NSArray arrayWithArray:[obj objectForKey:@"result"]];
                for (NSDictionary * dict in _contentArray) {
                    if ([[dict objectForKey:@"is_view"]intValue] == 1) {
                        [array addObject:dict];
                    }
                }
                [[DownloadArticle shareDownloadArticle]downloadMagaWithArray:array dict:self.magazineInfo];

            }

        }
        dispatch_async(dispatch_get_main_queue(), ^{

            ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"开始下载"]autorelease];
            [abp show];

        });
    });


}





- (IBAction)picButtonClicked:(id)sender {
    picVersionsButton.selected = YES;
    textVersionsButton.selected = NO;
    picView.hidden = NO;
    textTableView.hidden = YES;
}
- (IBAction)textButtonClicked:(id)sender {
    if (!textVersionArray || textVersionArray.count == 0) {
        [self getData];
    }
    picVersionsButton.selected = NO;
    textVersionsButton.selected = YES;
    picView.hidden = YES;
    textTableView.hidden = NO;

}
- (IBAction)downloadButtonClicked:(id)sender {
    NSLog(@"%@",textVersionArray);
    [[DownloadArticle shareDownloadArticle] downloadNewspaperWithArray:textVersionArray info:self.baseInfo];
    downloadButton.enabled = NO;
}

-(void)getData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (item_id && item_id.length != 0) {
            id obj = [[DataRequest sharedRequest] getNewspaperTextVersions:item_id];
            if ([obj isKindOfClass:[NSDictionary class]] && [[obj objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                textVersionArray = [[NSMutableArray alloc] initWithArray:[obj objectForKey:@"result"]];
            }

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"array:%@",textVersionArray);
            [textTableView reloadData];
            downloadButton.hidden = NO;
        });
    });

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return textVersionArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        static NSString * cellID = @"cellID";
        NewspaperTitleCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NewspaperTitleCell" owner:self options:0]lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.baseInfo = dict;
        [cell updateDisplay];
        return cell;

    }else{
        static NSString * cellID = @"cellID1";
        NewspaperDesCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NewspaperDesCell" owner:self options:0]lastObject];
        }
        
        cell.baseInfo = dict;
        [cell updateDisplay];
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        return 40;
    }else{
        CGSize size = [[dict objectForKey:@"page_name"] sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:CGSizeMake(310, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
        NSLog(@"high:%f",size.height);
        return size.height + 10;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        NSLog(@">>>>>>>>>>");
        return;
    }else{
        NewspaperSingleArticleViewController * newspaperSingleArticleViewController = [[[NewspaperSingleArticleViewController alloc]initWithNibName:@"NewspaperSingleArticleViewController" bundle:nil]autorelease];
        newspaperSingleArticleViewController.baseInfo = dict;
        newspaperSingleArticleViewController.titleStr = self.titleStr;
        [[UIApplication rootNavController] pushViewController:newspaperSingleArticleViewController animated:YES];
    }
}


- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView
{
    return self.picVersionArray.count;
}

-(AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index{
    static NSString * cellID = @"cellID";
    PicVersion * cell = (PicVersion *)[gridView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[PicVersion alloc]initWithFrame:CGRectMake(25, 30, picGridView.bounds.size.width, picGridView.bounds.size.height) reuseIdentifier:cellID];
    }
    cell.baseInfo = [_picVersionArray objectAtIndex:index];
    cell.index = index;
    cell.viewController = self;
    if (self.isHomePage) {
        [cell updateDisplayWithImageStr:@"cover_img" text:[[[_picVersionArray objectAtIndex:index] objectForKey:@"page_number"] integerValue]];

    }else{
        [cell updateDisplayWithImageStr:@"image" text:[[[_picVersionArray objectAtIndex:index] objectForKey:@"page_number"] integerValue]];
    }
//    NSLog(@"array:%@",self.picVersionArray);
    return cell;
}
- (CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView
{
    return picGridView.bounds.size;//CGSizeMake(320, [UIScreen mainScreen].bounds.size.height - 95);
}
- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index{
    
    
    [self showIndex:index];
//    [self.navigationController pushViewController:newspaperPicDesViewController animated:YES];
}

//- (void)didSelectCell:(NSNotification *)notification
//{
//    int index = [notification.object integerValue];
//    [self showIndex:index];
//}

- (void)showIndex:(int)index
{
    NewspaperPicDesViewController * newspaperPicDesViewController = [[[NewspaperPicDesViewController alloc]initWithNibName:@"NewspaperPicDesViewController" bundle:nil]autorelease];
    newspaperPicDesViewController.titleStr = self.titleStr;
    newspaperPicDesViewController.item_id = item_id;
    newspaperPicDesViewController.pageNumber = [[self.picVersionArray objectAtIndex:index] objectForKey:@"page_number"];
    NSLog(@"rootNavController>>>>%@",[UIApplication rootNavController]);
    [[UIApplication rootNavController] pushViewController:newspaperPicDesViewController animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [titleLabel release];
    [picVersionsButton release];
    [textVersionsButton release];
    [downloadButton release];
    [picGridView release];
    [textTableView release];
    [picView release];
    [backButton release];
    [headImage release];
    [self.baseInfo release];
    [self.magazineInfo release];
    [self.picVersionArray release];
    [historyButton release];
    [leftDownloadButton release];
    [super dealloc];
}
- (void)viewDidUnload {
    [titleLabel release];
    titleLabel = nil;
    [picVersionsButton release];
    picVersionsButton = nil;
    [textVersionsButton release];
    textVersionsButton = nil;
    [downloadButton release];
    downloadButton = nil;
    [picGridView release];
    picGridView = nil;
    [textTableView release];
    textTableView = nil;
    [picView release];
    picView = nil;
    [backButton release];
    backButton = nil;
    [headImage release];
    headImage = nil;
    [self.magazineInfo release];
    [self.picVersionArray release];
    [self.baseInfo release];
    
    [historyButton release];
    historyButton = nil;
    [leftDownloadButton release];
    leftDownloadButton = nil;
    [super viewDidUnload];
}
@end
